var Web_Book = function(options){

    this.module = options.module;
    this.controller = options.controller;
    this.urlPath = baseUrl + '/' + this.module + '/' + this.controller;
    this.sendding = false;
}

$.extend(Web_Book.prototype, {
    _eUnit: function(oForm){
        var self = this;
        $("#btnsave").unbind('click').click(function(){
                if($('#frmUpdateUnit')[0].checkValidity()){
                    self.saveUnit();
                    return false;
                }
            });
        self._getDep(oForm);
        self.keyupName($(oForm).find('#Name'));
    },
    _getDep: function(oForm){
        var self = this;
        $('.imgGetDep').click(function(e){
            var dialog = $('#dialog-dep');
            if (dialog.attr('loaded') == 0) {
               self.genTreeAdd($('#treeDialog'),oForm);
               dialog.attr('loaded',1);
            };
                dialog.lightbox_me({
                centered: true, 
                onLoad: function() { 
                    $('#sign_up').find('input:first').focus()
                    }
                });
                e.preventDefault();
        })
    },
    keyupName: function(obj){
        $(obj).keyup(function(e) {
            /* Act on the event */
            if(e.keyCode = 8)
            {
                var R14 = toPascalCase($(this).val());
                $(this).val(R14);
            }
        });
    },
    _eStaff: function(oForm){
        var self = this;
        $('#changepass').click(function() {
            self.changepass();
        });

        $("#btnsavestaff").unbind('click').click(function(){
            if($('#frmUpdateStaff')[0].checkValidity()){
                self.saveStaff();
                return false;
            }
        });

        $('#Birthday').datepicker({
                changeMonth: true,
                gotoCurrent: true,
                minDate: new Date(2010, 1 - 1, 1),
                maxDate:'today',
                changeYear: true
            });
        $('#Username').change(function(){
            self.checkUserName($(this).val());
        })
        self._getDep(oForm);
        self.keyupName($(oForm).find('#Name'));
    },
    checkUserName: function(username){
        $.ajax({
            url: this.urlPath + '/checkuser',
            type: "POST",
            data: {username: username},
            success: function(resp){
                if (resp > 0) {
                    document.getElementById('Username').setCustomValidity('Tên đăng nhập đã tồn tại!');
                }else {
                    document.getElementById('Username').setCustomValidity('');
                };
            }
        });
    },
    _eIndex: function(){
        var self = this;
        $('#refreshTree').click(function(){
            self.refreshTree();
        })
    }
} );

Web_Book.prototype.refreshTree = function (){
    var self = this
        ,url = this.urlPath + '/refresh';
    $.ajax({
        url: url,
        type: "POST",
        success: function(data){
            $("#jsTree").jstree("refresh");
            dLayout.hideLoadPage();
        },
        beforeSend: function(xhr) {
            dLayout.showLoadPage();
        },
        errors: function(){
            dLayout.hideLoadPage();
        }
    }); 
}
/*
 * Them moi
 * Creater : TuanPm
 */

Web_Book.prototype.addUnit = function(idNode,nameNode){
    var self = this
        ,url = this.urlPath + '/add'
        ,data = [];
    var act = 'add';
    data = {
        idNode : idNode,
        nameNode : nameNode,
        act:act,
    };
    // alert($('#idNode').val());
    $.ajax({
        url: url,
        type: "POST",
        data: data,
        success: function(string){
            $('div#right_sileBar').html(string);
            self._eUnit($('#frmUpdateUnit'));
            dLayout.hideLoadPage();
        },
        beforeSend: function(xhr) {
            dLayout.showLoadPage();
        },
        errors: function(){
            dLayout.hideLoadPage();
        }
    });
     return !history.pushState;
}
Web_Book.prototype.edit = function(idNode,nameNode){
    var self = this
        ,url = this.urlPath + '/add'
        ,data = [];
    var act = 'edit';
    data = {
        idNode : idNode,
        nameNode : nameNode,
        act : act,
    };
    // alert($('#idNode').val());
    $.ajax({
        url: url,
        type: "POST",
        data: data,
        success: function(string){
            $('div#right_sileBar').html(string);
           // $('form#frmUpdateUnit').show();
           self._eUnit($('#frmUpdateUnit'));
        },
    });
     return !history.pushState;
}


Web_Book.prototype.saveUnit = function(){
    var self = this
        ,url = this.urlPath + '/save'
        ,data = $('form#frmUpdateUnit').serialize();
    data += '&idNode=' + $('#idNode').val();
    data += '&idName=' + $('#idName').val();
    $.ajax({
        url: url,
        type: "POST",
        data: data,
        // dataType: 'json',
        success: function(errors){
            // errors = $.parseJSON(errors);
            // if(errors.length){
            //    alert($('label[for="Code"]').text() + ' ' + errors['0']['Code']);
            // }else{
            //     document.getElementById('frmUpdateUnit').reset();
            // }
            $("#jsTree").jstree("refresh");
            dLayout.hideLoadPage();
        },
        beforeSend: function(xhr) {
            dLayout.showLoadPage();
        },
        errors: function(){
            dLayout.hideLoadPage();
        }
    });
     return !history.pushState; // ngăn việc chuyển trang thực sự nếu trình duyệt có hỗ trợ pushState
}
Web_Book.prototype.delete = function(nodeList){
    var self = this
        ,url = this.urlPath + '/delete'
        ,data = []
        ,row;
    if(confirm("Bạn có chắc chắn muốn Xóa các phòng ban này!")){
        $.ajax({
            url: url,
            type: "POST",
            data: {nodeList:nodeList},
            success: function(string){
                if(string){
                    alert(string);
                    return false;
                }
                $("#jsTree").jstree("refresh");
            },
        });
    }
     return !history.pushState;
}
Web_Book.prototype.addStaff = function(idNode,nameNode){
    var self = this
        ,url = this.urlPath + '/addstaff'
        ,data = []
        ,oForm = $('#frmUpdateStaff');
    var act = 'addstaff';
    data = {
        idNode : idNode,
        nameNode : nameNode,
        act:act,
    };
    $.ajax({
        url: url,
        type: "POST",
        data: data,
        success: function(string){
            $('div#right_sileBar').html(string);
            self._eStaff($('form#frmUpdateStaff'));
        },
    });
     return !history.pushState;
}
Web_Book.prototype.editstaff = function(idNode,nameNode){
    var self = this
        ,url = this.urlPath + '/addstaff'
        ,data = [],oForm = $('#frmUpdateStaff');
    var act = 'editstaff';
    data = {
        idNode : idNode,
        nameNode : nameNode,
        act : act,
    };
    // alert($('#idNode').val());
    $.ajax({
        url: url,
        type: "POST",
        data: data,
        success: function(string){
            $('div#right_sileBar').html(string);
            self._eStaff($('form#frmUpdateStaff'));
        },
    });
     return !history.pushState;
}
Web_Book.prototype.saveStaff = function(){
    var self = this
        ,url = this.urlPath + '/savestaff'
        ,data = $('form#frmUpdateStaff').serialize();
    data += '&idNode=' + $('#idNode').val();
    data += '&idName=' + $('#idName').val();
    $.ajax({
        url: url,
        type: "POST",
        data: data,
        // dataType: 'json',
        success: function(errors){
            $("#jsTree").jstree("refresh");
            dLayout.hideLoadPage();
        },
        beforeSend: function(xhr) {
            dLayout.showLoadPage();
        },
        errors: function(){
            dLayout.hideLoadPage();
        }
    });
     return !history.pushState; // ngăn việc chuyển trang thực sự nếu trình duyệt có hỗ trợ pushState
}
Web_Book.prototype.deletestaff = function(nodeList){
    var self = this
        ,url = this.urlPath + '/deletestaff'
        ,data = []
        ,row;
    if(confirm("Bạn có chắc chắn muốn Xóa các User ban này!")){
        $.ajax({
            url: url,
            type: "POST",
            // dataType:'json',
            data: {nodeList:nodeList},
            success: function(string){
                if(string){
                        alert(string);
                        return false;
                    }
                $("#jsTree").jstree("refresh");
            },
        });
    }
     return !history.pushState;
}
function toPascalCase(str) {
    var arr = str.split(/\s|_/);
    for(var i=0,l=arr.length; i<l; i++) {
        arr[i] = arr[i].substr(0,1).toUpperCase() +
                 (arr[i].length > 1 ? arr[i].substr(1).toLowerCase() : "");
    }
    return arr.join(" ");
}
// function createModalDialog(obj,functioncall){
//     if($(obj).parent('[role="dialog"]').length ===0){
//         functioncall();
//     }else{
//         $(obj).parent('[role="dialog"]').find(obj).remove();
//         $(obj).parent('[role="dialog"]').remove();
//         functioncall();
//     }
// }

Web_Book.prototype.genTreeAdd = function(obj,oForm){
    var url = this.urlPath + '/loadtree';
    obj.jstree({ "plugins" : ["themes","json_data","ui","crrm","search","types","hotkeys"],
            "json_data" : {
                "ajax" : {
                    "url" : url,
                    "data" : function (n) {
                        return {
                            "operation" : "get_children",
                            "id" : n.attr ? n.attr("id").replace("node_","") : '',
                            "sType":'unit',
                        };
                    }
                }
            }
            ,"types" : {
                "max_depth" : -2,
                "max_children" : -2,
                "valid_children" : [ "drive" ],
                "types" : {
                    "user" : {
                        "icon" : {
                            "image" : "../../../public/images/Users.png"
                        }
                    },
                    "group" : {
                        "icon" : {
                            "image" : "../../../public/images/user_group.png",
                            "check_node" : false,
                            "uncheck_node" : false
                        }
                    },
                    "home" : {
                               "icon" : {
                                   "image" : "../../../public/images/home.png",
                                   "check_node" : false,
                                   "uncheck_node" : false
                               }
                           } ,
                },
                "default" : {
                    "valid_children" : [ "default" ]
                }
            }
        })
        .bind("select_node.jstree", function (event, data) {
            $('#selectTree').val(data.rslt.obj.attr("id"));
            resulter = data.inst.get_text(data.rslt.obj);
            oForm.find('input#parentUnit').val(resulter);
            obj.jstree("toggle_node", data.rslt.obj);

        })
        .delegate("a", "click", function (event, data) {
            event.preventDefault(); })
        .delegate("a","dblclick", function(e) {
            $('#dialog-dep').trigger('close');
        });

}
Web_Book.prototype.changepass = function(){
    var url = this.urlPath + '/changepass';
    var self = this, nodeList='', data = [];
    nodeList = $('#idNode').val();
    $.ajax({
        url: url,
        type: "POST",
        // dataType:'json',
        data: {nodeList:nodeList},
        success: function(resp){
            if (resp) {
                alert('Thay đổi thành công!');
            };
            dLayout.hideLoadPage();
        },
        beforeSend: function(xhr) {
            dLayout.showLoadPage();
        },
        errors: function(){
            dLayout.hideLoadPage();
        }
    });
     return !history.pushState;

}

